#pragma once

#include <iostream>
#include <string>
#include <fstream>
#include "Log.hpp"
#include <unordered_map>
#include "InetAddr.hpp"

const std::string default_dict_path = "dictionary.txt";

std::string sep = ":";

using namespace LogModule;

class Dict
{
public:
    Dict(const std::string path = default_dict_path)
    :_path(path)
    {}

    bool DictLoad()
    {
        std::ifstream in(_path);
        if(!in.is_open())
        {
            LOG(LogLevel::ERROR) << "open" << _path << "error!";
            return false;
        }

        std::string line;
        while(std::getline(in, line))
        {
            if(line.empty()) continue;
            auto pos = line.find(sep);
            if(pos == std::string::npos) continue;
            std::string key = line.substr(0, pos);
            std::string value = line.substr(pos + 1);
            if(key.empty() || value.empty()) 
            {
                LOG(LogLevel::DEBUG) << "不能解析: " << line;
            }
            _dict.insert(std::make_pair(key, value));
        }
        in.close();
        return true;
    }

    std::string Translate(const std::string &word, InetAddr &client)
    {
        auto iter = _dict.find(word);
        if(iter == _dict.end())
        {
            return "none";
        }
        LOG(LogLevel::DEBUG) << "进入到了翻译模块, [" << client.ip() << " : " << client.port() << "]# " <<  word << "->" << iter->second;
        return iter->second;
    }

    ~Dict()
    {}
private:
    const std::string _path;
    std::unordered_map<std::string, std::string> _dict;
};